import axios from 'axios'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8090/api'

// 创建axios实例
const api = axios.create({
    baseURL: API_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('auth_token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        if (error.response?.status === 401) {
            // 清除本地存储的认证信息
            localStorage.removeItem('auth_token')
            localStorage.removeItem('auth_user')
            // 可以在这里添加重定向到登录页的逻辑
        }
        return Promise.reject(error)
    }
)

export default {
    login: (credentials) => {
        return api.post('/auth/login', credentials)
    },
    register: (userData) => {
        return api.post('/auth/register', userData)
    },
    logout: () => {
        return api.post('/auth/logout')
    },
    getCurrentUser: () => {
        return api.get('/auth/me')
    }
}
